<template>
  <div>
    <div class="login-container">
      <!-- 左侧背景 -->
      <div class="left-section">
        <transition-group name="fade">
          <img v-for="(bg, index) in backgroundImages" :key="index" :src="bg"
            :class="['bg-image', { active: currentBgIndex === index }]" alt="京剧背景">
        </transition-group>
        <div class="content-overlay"></div>
      </div>

      <!-- 右侧登录区域 -->
      <div class="right-section">
        <div class="right-content">
          <!-- 标题部分 -->
          <div class="title-section">
            <h1>京剧苑</h1>
            <p>传承国粹 · 弘扬文化</p>
          </div>

          <!-- 登录表单 -->
          <div class="login-box">
            <h2 class="form-title">用户登录</h2>
            <el-tabs v-model="activeTab" class="login-tabs">
              <!-- 账号密码登录 -->
              <el-tab-pane label="账号密码" name="account">
                <el-form ref="accountForm" :model="accountForm" :rules="accountRules">
                  <el-form-item prop="username">
                    <el-input v-model="accountForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
                  </el-form-item>
                  <el-form-item prop="password">
                    <el-input v-model="accountForm.password" type="password" placeholder="请输入密码"
                      prefix-icon="el-icon-lock" show-password></el-input>
                  </el-form-item>
                  <el-form-item prop="agreeToTerms" class="terms-item">
                    <el-checkbox v-model="accountForm.agreeToTerms">
                      我已阅读并同意
                      <a href="javascript:;" @click.prevent="showTermsDialog = true" class="terms-link">服务条款</a>
                      和
                      <a href="javascript:;" @click.prevent="showPrivacyDialog = true" class="terms-link">隐私政策</a>
                    </el-checkbox>
                  </el-form-item>
                  <div class="remember-forgot">
                    <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                    <router-link to="/forgot-password" class="forgot-link">忘记密码？</router-link>
                  </div>
                  <el-button type="primary" @click="handleAccountLogin" :loading="loading">登录</el-button>
                </el-form>
              </el-tab-pane>

              <!-- 手机号登录 -->
              <el-tab-pane label="手机号" name="phone">
                <el-form ref="phoneForm" :model="phoneForm" :rules="phoneRules">
                  <el-form-item prop="phone">
                    <el-input v-model="phoneForm.phone" placeholder="请输入手机号"
                      prefix-icon="el-icon-mobile-phone"></el-input>
                  </el-form-item>
                  <el-form-item prop="code">
                    <div class="code-input-group">
                      <el-input v-model="phoneForm.code" placeholder="请输入验证码" prefix-icon="el-icon-key"></el-input>
                      <el-button class="code-btn" @click="sendPhoneCode" :disabled="phoneCodeTimer > 0">
                        {{ phoneCodeTimer > 0 ? `${phoneCodeTimer}s` : '获取验证码' }}
                      </el-button>
                    </div>
                  </el-form-item>
                  <el-form-item prop="agreeToTerms" class="terms-item">
                    <el-checkbox v-model="phoneForm.agreeToTerms">
                      我已阅读并同意
                      <a href="javascript:;" @click.prevent="showTermsDialog = true" class="terms-link">服务条款</a>
                      和
                      <a href="javascript:;" @click.prevent="showPrivacyDialog = true" class="terms-link">隐私政策</a>
                    </el-checkbox>
                  </el-form-item>
                  <el-button type="primary" @click="handlePhoneLogin" :loading="loading">登录</el-button>
                </el-form>
              </el-tab-pane>

              <!-- 邮箱登录 -->
              <el-tab-pane label="邮箱" name="email">
                <el-form ref="emailForm" :model="emailForm" :rules="emailRules">
                  <el-form-item prop="email">
                    <el-input v-model="emailForm.email" placeholder="请输入邮箱" prefix-icon="el-icon-message"></el-input>
                  </el-form-item>
                  <el-form-item prop="code">
                    <div class="code-input-group">
                      <el-input v-model="emailForm.code" placeholder="请输入验证码" prefix-icon="el-icon-key"></el-input>
                      <el-button class="code-btn" @click="sendEmailCode" :disabled="emailCodeTimer > 0">
                        {{ emailCodeTimer > 0 ? `${emailCodeTimer}s` : '获取验证码' }}
                      </el-button>
                    </div>
                  </el-form-item>
                  <el-form-item prop="agreeToTerms" class="terms-item">
                    <el-checkbox v-model="emailForm.agreeToTerms">
                      我已阅读并同意
                      <a href="javascript:;" @click.prevent="showTermsDialog = true" class="terms-link">服务条款</a>
                      和
                      <a href="javascript:;" @click.prevent="showPrivacyDialog = true" class="terms-link">隐私政策</a>
                    </el-checkbox>
                  </el-form-item>
                  <el-button type="primary" @click="handleEmailLogin" :loading="loading">登录</el-button>
                </el-form>
              </el-tab-pane>
            </el-tabs>

            <div class="register-link">
              还没有账号？<router-link to="/register">立即注册</router-link>
            </div>
          </div>
        </div>
      </div>
    </div>

    <service-terms-dialog v-model="showTermsDialog" type="terms" />

    <service-terms-dialog v-model="showPrivacyDialog" type="privacy" />
  </div>
</template>



<script>
import bg1 from '@/assets/opera_bg1.jpg'
import bg2 from '@/assets/opera_bg2.jpg'
import bg3 from '@/assets/opera_bg3.jpg'

import service from '@/utils/request'
import ServiceTermsDialog from '@/components/ServiceTermsDialog.vue'
import CryptoJS from 'crypto-js'  // 添加这行导入


export default {
  components: {
    ServiceTermsDialog
  },
  data() {
    return {
      activeTab: 'account',
      loading: false,
      rememberMe: false,
      phoneCodeTimer: 0,
      emailCodeTimer: 0,
      backgroundImages: [bg1, bg2, bg3],
      currentBgIndex: 0,
      bgRotationTimer: null,
      accountForm: {
        username: '',
        password: '',
        agreeToTerms: false
      },
      phoneForm: {
        phone: '',
        code: '',
        agreeToTerms: false
      },
      emailForm: {
        email: '',
        code: '',
        agreeToTerms: false
      },
      accountRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        agreeToTerms: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请阅读并同意服务条款和隐私政策'));
              } else {
                callback();
              }
            }, trigger: 'change'
          }
        ]
      },
      phoneRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
        ],
        agreeToTerms: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请阅读并同意服务条款和隐私政策'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      },
      emailRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
        ],
        agreeToTerms: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请阅读并同意服务条款和隐私政策'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      },
      showTermsDialog: false,
      showPrivacyDialog: false
    }
  },
  mounted() {
    // 设置页面标题
    document.title = '京剧苑 - 用户登录';
    // 启动背景图轮播
    this.startBackgroundRotation();
    // 检查 localStorage 中是否有记住的用户名和密码
    const savedUsername = localStorage.getItem('savedUsername');
    const savedPassword = localStorage.getItem('savedPassword');
    if (savedUsername) {
      this.accountForm.username = savedUsername;
    }
    if (savedPassword) {
      this.accountForm.password = savedPassword;
      this.rememberMe = true; // 如果有密码，设置记住我为 true
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.bgRotationTimer) {
      clearInterval(this.bgRotationTimer);
    }
  },
  methods: {
    // 开始背景图轮播
    startBackgroundRotation() {
      this.bgRotationTimer = setInterval(() => {
        this.currentBgIndex = (this.currentBgIndex + 1) % this.backgroundImages.length;
      }, 5000);
    },
    // 账号密码登录
    handleAccountLogin() {
      this.$refs.accountForm.validate(valid => {
        if (valid) {
          if (!this.accountForm.agreeToTerms) {
            this.$message.error('请阅读并同意服务条款和隐私政策');
            return;
          }
          this.loading = true;
          const loginData = {
            ...this.accountForm,
            password: CryptoJS.MD5(this.accountForm.password).toString()
          };
          service.post('/api/system/user/login/account', loginData)
            .then(res => {
              if (res.code === 200) {
                localStorage.setItem('token', res.data);
                // 如果选择了记住我，保存用户名和密码
                if (this.rememberMe) {
                  localStorage.setItem('savedUsername', this.accountForm.username);
                  localStorage.setItem('savedPassword', this.accountForm.password);
                } else {
                  localStorage.removeItem('savedUsername');
                  localStorage.removeItem('savedPassword');
                }
                this.getUserInfo();
              }
            })
            .catch(err => {
              this.$message({
                message: '登录失败，请稍后重试',
                type: 'error',
                customClass: 'message-top-right'
              });
              console.error(err);
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    // 手机号登录
    handlePhoneLogin() {
      this.$refs.phoneForm.validate(valid => {
        if (valid) {
          if (!this.phoneForm.agreeToTerms) {
            this.$message.error('请阅读并同意服务条款和隐私政策');
            return;
          }
          this.loading = true;
          // 直接使用手机号和验证码进行登录
          service.post('/api/system/user/login/phone', this.phoneForm)
            .then(res => {
              if (res.code === 200) {
                localStorage.setItem('token', res.data);
                // 获取用户个人信息
                this.getUserInfo();
              } 
            })
            .catch(err => {
              this.$message.error('登录失败，请稍后重试');
              console.error(err);
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    // 邮箱登录
    handleEmailLogin() {
      this.$refs.emailForm.validate(valid => {
        if (valid) {
          if (!this.emailForm.agreeToTerms) {
            this.$message.error('请阅读并同意服务条款和隐私政策');
            return;
          }
          this.loading = true
          // 直接使用邮箱和验证码进行登录
          service.post('/api/system/user/login/email', this.emailForm)
            .then(res => {
              console.log(res)
              if (res.code === 200) {
                localStorage.setItem('token', res.data);
                // 获取用户个人信息
                this.getUserInfo();
              } 
            })
            .catch(err => {
              this.$message.error('登录失败，请稍后重试');
              console.error(err);
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    // 发送手机验证码
    sendPhoneCode() {
      this.$refs.phoneForm.validateField('phone', valid => {
        if (!valid) {
          service.get('/api/system/verification/send-phone-code', {
            params: {
              phone: this.phoneForm.phone
            }
          })
            .then(res => {
              if (res.code === 200) {
                this.$message.success('验证码已发送')
                this.phoneCodeTimer = 60
                const timer = setInterval(() => {
                  this.phoneCodeTimer--
                  if (this.phoneCodeTimer <= 0) {
                    clearInterval(timer)
                  }
                }, 1000)
              } 
            })
            .catch(err => {
              this.$message.error('发送失败，请稍后重试')
              console.error(err)
            })
        }
      })
    },

    // 发送邮箱验证码
    sendEmailCode() {
      this.$refs.emailForm.validateField('email', valid => {
        if (!valid) {
          // 立即启动倒计时
          this.emailCodeTimer = 60;
          const timer = setInterval(() => {
            this.emailCodeTimer--;
            if (this.emailCodeTimer <= 0) {
              clearInterval(timer);
            }
          }, 1000);

          // 发送验证码请求
          service.get('/api/system/verification/send-email-code', {
            params: {
              email: this.emailForm.email
            }
          })
            .then(res => {
              if (res.code === 200) {
                this.$message.success('验证码已发送');
              } 
            })
            .catch(err => {
              this.$message.error('发送失败，请稍后重试');
              console.error(err);
              // 如果请求失败，重置倒计时
              clearInterval(timer);
              this.emailCodeTimer = 0;
            });
        }
      });
    },
    getUserInfo() {
      service.get('/api/system/user/profile', {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      })
        .then(res => {
          if (res.code === 200) {
            localStorage.setItem('screenName', res.data.screenName);
            localStorage.setItem('avatar', res.data.avatar);
            localStorage.setItem('roletype', res.data.roleId);
            this.$router.push('/');
            this.$message.success('登录成功');
          }
        })
        .catch(err => {
          this.$message.error('获取用户信息失败，请稍后重试');
          console.error(err);
        })
    }
  }
}
</script>

<style>
/* 全局样式 */
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

#app {
  height: 100%;
  width: 100%;
}
</style>

<style scoped>
.login-container {
  display: flex;
  min-height: 100vh;
  width: 100vw;
  overflow: hidden;
}

/* 左侧样式 */
.left-section {
  flex: 1.2;
  position: relative;
  overflow: hidden;
}

.bg-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.bg-image.active {
  opacity: 1;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 1s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.content-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(139, 0, 0, 0.6), rgba(0, 0, 0, 0.6));
}

/* 右侧样式 */
.right-section {
  width: 550px;
  background: linear-gradient(135deg, #8B0000 0%, #4A0404 100%);
  padding: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.right-content {
  width: 100%;
  max-width: 400px;
}

/* 标题样式 */
.title-section {
  text-align: center;
  margin-bottom: 40px;
  position: relative;
}

.title-section h1 {
  font-family: 'STXingkai', 'STZhongsong', serif;
  font-size: 48px;
  color: #FFD700;
  margin: 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  letter-spacing: 8px;
  padding-bottom: 15px;
  position: relative;
}

.title-section h1::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 180px;
  height: 2px;
  background: linear-gradient(90deg,
      transparent,
      rgba(255, 215, 0, 0.3),
      #FFD700,
      rgba(255, 215, 0, 0.3),
      transparent);
}

.title-section p {
  font-size: 18px;
  color: #FFD700;
  margin-top: 15px;
  font-family: 'STZhongsong', sans-serif;
  letter-spacing: 4px;
}

/* 表单主标题 */
.form-title {
  text-align: center;
  color: #FFD700;
  font-size: 24px;
  margin: 0 0 20px;
  font-family: 'STZhongsong', sans-serif;
  letter-spacing: 2px;
}


/* 登录框样式 */
.login-box {
  background: rgba(0, 0, 0, 0.2);
  padding: 30px;
  border-radius: 10px;
  border: 1px solid rgba(255, 215, 0, 0.3);
}

/* 标签页样式 */
.login-tabs>>>.el-tabs__nav {
  width: 100%;
  display: flex;
}

.login-tabs>>>.el-tabs__item {
  flex: 1;
  text-align: center;
  color: #FFD700;
  font-size: 16px;
  padding: 0 0 12px;
  font-family: 'STZhongsong', sans-serif;
}

.login-tabs>>>.el-tabs__item.is-active {
  color: #FFD700;
  font-weight: bold;
}

.login-tabs>>>.el-tabs__active-bar {
  background-color: #FFD700;
  height: 2px;
}

.login-tabs>>>.el-tabs__nav-wrap::after {
  background-color: rgba(255, 215, 0, 0.2);
}

.login-tabs>>>.el-tabs__header {
  margin-bottom: 30px;
}

/* 输入框样式 */
.el-input>>>.el-input__inner {
  height: 45px;
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 215, 0, 0.3);
  color: #fff;
  border-radius: 6px;
  padding-left: 45px;
  font-size: 15px;
}

.el-input>>>.el-input__inner:focus {
  border-color: #FFD700;
}

.el-input>>>.el-input__prefix {
  color: #FFD700;
  font-size: 18px;
  left: 15px;
}

/* 验证码按钮样式 */
.code-input-group {
  display: flex;
  gap: 10px;
}

.code-input-group .el-input {
  flex: 1;
}

.code-btn {
  width: 100px !important;
  height: 45px !important;
  background: linear-gradient(135deg, #8B0000 0%, #4A0404 100%) !important;
  border: 1px solid #FFD700 !important;
  color: #FFD700 !important;
  font-size: 14px !important;
  padding: 0 15px !important;
  border-radius: 6px !important;
  transition: all 0.3s !important;
}

.code-btn:hover:not([disabled]) {
  opacity: 0.9;
  border-color: #fff !important;
  color: #fff !important;
}

.code-btn[disabled] {
  background: rgba(139, 0, 0, 0.5) !important;
  border-color: rgba(255, 215, 0, 0.3) !important;
  color: rgba(255, 215, 0, 0.5) !important;
  cursor: not-allowed;
}

/* 记住我和忘记密码 */
.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0;
}

.el-checkbox>>>.el-checkbox__label {
  color: #FFD700;
}

.el-checkbox>>>.el-checkbox__inner {
  background-color: transparent;
  border: 1px solid #FFD700;
}

.forgot-link {
  color: #FFD700;
  text-decoration: none;
  font-size: 14px;
}

/* 登录按钮 */
.el-button--primary {
  width: 100%;
  height: 45px;
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid #FFD700;
  font-size: 16px;
  letter-spacing: 4px;
  border-radius: 6px;
  margin-top: 15px;
  color: #FFD700;
}

.el-button--primary:hover {
  background: rgba(0, 0, 0, 0.3);
}

/* 注册链接 */
.register-link {
  text-align: center;
  margin-top: 20px;
  color: rgba(255, 215, 0, 0.8);
  font-size: 14px;
}

.register-link a {
  color: #FFD700;
  text-decoration: none;
  margin-left: 5px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .right-section {
    width: 500px;
  }

  .title-section h1 {
    font-size: 42px;
  }
}

@media (max-width: 992px) {
  .left-section {
    display: none;
  }

  .right-section {
    width: 100%;
  }
}

@media (max-width: 576px) {
  .right-section {
    padding: 20px;
  }

  .login-box {
    padding: 20px;
  }

  .title-section h1 {
    font-size: 36px;
  }
}

.terms-item {
  margin: 15px 0;
}

.terms-link {
  color: #ff0000;
  /* text-decoration: none; */
  cursor: pointer;

}

.terms-link:hover {
  text-decoration: underline;
}

/* 弹窗样式覆盖 */
:deep(.el-dialog) {
  background: linear-gradient(135deg, #8B0000 0%, #4A0404 100%);
  border: 1px solid rgba(255, 215, 0, 0.3);
}

:deep(.el-dialog__title) {
  color: #FFD700;
}

:deep(.el-dialog__body) {
  color: #fff;
}
</style>